package com.googlecode.openrtp.spi.rtcp;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import com.googlecode.openrtp.spi.PacketUtil;

/**
 *
 *   0                   1                   2                   3
 *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 * |V=2|P|    SC   |  PT=SDES=202  |             length            | header
 * +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
 *
 * @author jocke
 */
public class RtcpSourceDescriptionPacket implements RtcpPacket {

    private final RtcpHeaderPacket headerPacket;
    private final Map<Long, SourceDescription> items;

    private RtcpSourceDescriptionPacket(RtcpHeaderPacket packet, Map<Long, SourceDescription> items) {
        this.headerPacket = packet;
        this.items = items;
        Objects.requireNonNull(items);
        Objects.requireNonNull(packet);
    }

    public static RtcpSourceDescriptionPacket create(RtcpHeaderPacket packet, Map<Long, SourceDescription> items) {
        return new RtcpSourceDescriptionPacket(packet, items);
    }

    public static RtcpSourceDescriptionPacket create(Map<Long, SourceDescription> items) throws UnsupportedEncodingException {
        RtcpHeaderPacket packet = RtcpHeaderPacket.create(
                RtcpHeaderPacket.FINAL_VERSION,
                0,
                items.size(),
                RtcpHeaderPacket.PT.SOURCE_DESC,
                getLength(items));
        return new RtcpSourceDescriptionPacket(packet, items);
    }

    public Map<Long, SourceDescription> getItems() {
        return Collections.unmodifiableMap(items);
    }

    public RtcpHeaderPacket getHeaderPacket() {
        return headerPacket;
    }

    private static int getLength(Map<Long, SourceDescription> items) throws UnsupportedEncodingException {
        int length = 0;
        length += getLengthOfItems(items);
        length += RtcpHeaderPacket.PACKET_LENGTH;
        return (length / 4) -1;
    }

    private static int getLengthOfItems(Map<Long, SourceDescription> items) throws UnsupportedEncodingException {
        int length = 0;
        for (Map.Entry<Long, SourceDescription> entry : items.entrySet()) {
            length += entry.getValue().getChunkLength();
        }

        return length;
    }

    @Override
    public String toString() {
        return "RtcpSourceDescriptionPacket{" + "headerPacket=" + headerPacket + ", items=" + items + '}';
    }
}
